#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include "libapogee.h"

int main(){
	if(ApnGlueOpen(1)){
		printf("Can't open, exit\n");
		return 0;
	}
	char *sensor, *camera;
	ApnGlueGetName(&sensor, &camera);
	printf("camera: %s, sensor: %s\n", camera, sensor);
	double temp;
	int stat = ApnGlueGetTemp(&temp);
	printf("stat = %d, temp=%g\n", stat, temp);
	int roih, roiw, osh, osw, binh, binw, shutter;
	double mintemp;
	ApnGlueSetFan(0);
	//ApnGlueSetFan(3);
	ApnGlueGetMaxValues (NULL, &roiw, &roih, &osw, &osh, &binw, &binh,
		&shutter, &mintemp);
	printf("roiw=%d, roih=%d, osw=%d, osh=%d, binw=%d, binh=%d, mintemp=%g\n",
		roiw, roih, osw, osh, binw, binh, mintemp);
	//ApnGlueSetTemp(-30.);
	/*int s = 0;
	do{
		stat = ApnGlueGetTemp(&temp);
		printf("%ds: stat = %d, temp=%g\n", s++, stat, temp);
		sleep(1);
	}while(stat != 2 || fabs(temp+30) > 0.2);*/
	int imW, imH;
	char  whynot[256];
	unsigned short *buf = NULL;
	if(ApnGlueSetExpGeom (1000, 1000, 0, 0, 0, 0, 1000, 1000, &imW, &imH, whynot))
		printf("ERR set geom: %s\n", whynot);
	else do{
		double exptime = 0.03;
		int L = imW*imH;
		buf = (unsigned short*) calloc(L, sizeof(unsigned short));
		if(ApnGlueStartExp(&exptime, 1)){
			printf("Can't expose\n");
			break;
		}
		printf("Start exp [%dx%d]: %g seconds ", imW, imH, exptime);
		while(!ApnGlueExpDone()){
			stat = ApnGlueGetTemp(&temp);
			printf("stat = %d, temp=%g\n", stat, temp);
			fflush(stdout); sleep(1);}
		printf(" done\nGet image\n");
		if(ApnGlueReadPixels(buf, L, whynot)){
			printf("Error read: %s\n", whynot);
			break;
		}
		printf("buf(%d, %d) = %hu\n", imW/2, imH/2, buf[L/2]);
	}while(0);
	free(buf);
	ApnGlueSetTemp(0);
	ApnGlueSetFan(0);
}
